package com.mewp.permissions.system.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mewp.permissions.common.entity.Result;
import com.mewp.permissions.common.entity.ResultCodeEnum;
import com.mewp.permissions.common.utils.JwtHelper;
import com.mewp.permissions.common.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 认证解析token过滤器
 *
 * @author mewp
 * @version 1.0
 * @date 2023/8/4 00:58
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //如果是登录接口，直接放行
        if ("/admin/system/index/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            String userName = JwtHelper.getUserName(token);
            if (StringUtils.hasText(userName)) {
                String authoritiesString = (String) redisTemplate.opsForValue().get(userName);
                try {
                    List<Map<String, String>> mapList = new ObjectMapper().readValue(authoritiesString, new TypeReference<>() {
                    });
                    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                    for (Map<String, String> map : mapList) {
                        authorities.add(new SimpleGrantedAuthority(map.get("authority")));
                    }
                    return new UsernamePasswordAuthenticationToken(userName, null, authorities);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException("获取权限失败");
                }
            }
        }
        return null;
    }
}
